import re
import json
import requests
from bs4 import BeautifulSoup

week_dict={'星期一':1,'星期二':2,'星期三':3,'星期四':4,'星期五':5,'星期六':6,'星期日':7}

def parse_courses_html(uid,html_file):
    try:
        data = html_file.read()
    except Exception as e:
        print('parse courses read html error:',e)
        return None
    finally:
        html_file.close()

    table = BeautifulSoup(data,'html.parser').find('table')
    if table == None:
        return None

    trs = table.find_all('tr')

    json_list = []

    for tr in trs:
        item_list = tr.find_all('td')
        print('course item list size:',len(item_list))
        if len(item_list) < 10:
            continue

        time_list = item_list[5].get_text(' ').split(' ')
        loc_list = item_list[6].get_text(' ').split(' ')

        if len(time_list)%3 == 0 :
            for i in range(0,int(len(time_list)/3)) :
                terms = item_list[0].get_text(strip = True).split(' ')
                schoolYear = '--' if len(terms) < 2 else terms[0]
                term = '--' if len(terms) < 2 else terms[1]
                cid = '--' if len(item_list[1].get_text(strip = True)) == 0 else item_list[1].get_text(strip = True)
                cn = '--' if len(item_list[2].get_text(strip = True)) == 0 else item_list[2].get_text(strip = True)
                period = '--' if len(item_list[3].get_text(strip = True)) == 0 else item_list[3].get_text(strip = True)
                credit =  0.0 if len(item_list[4].get_text(strip = True)) == 0 else float(item_list[4].get_text(strip = True))

                pattern = re.compile(r'\d{1,2}')#提取时间字符串中的数字
                week = pattern.findall(time_list[0+i*3])
                section = pattern.findall(time_list[2+i*3])

                bs = 0 if len(section) == 0 else int(section[0])
                es = 0 if len(section) == 0 else int(section[1])
                bw = 0 if len(week) == 0 else int(week[0])
                ew = 0 if len(week) == 0 else int(week[1])

                # dayStr=time_list[1+i*3]
                # print('day is:',dayStr)
                day = week_dict.get(time_list[1+i*3])

                cr = loc_list[1+i*2]
                teacher = u'--' if len(item_list[7].get_text(strip = True)) == 0 else item_list[7].get_text('|').split('|')[0]
                campus = u'--'  if len(item_list[8].get_text(strip = True)) == 0 else item_list[8].get_text(strip = True)
                sty = u'正常' if len(item_list[9].text) == 0 else item_list[9].text
                sm = u'初修' if len(item_list[10].text) == 0 else item_list[10].text

                if sty != u'免听':
                    json_list.append({'uid':uid,'schoolYear':schoolYear,'term':term,'cid':cid,'cname':cn,'period':period,'credit':credit,
                    'startSection':bs,'endSection':es,'startWeek':bw,'endWeek':ew,'dayOfWeek':day,'classroom':cr,'teacher':teacher,
                    'campus':campus,'studyType':sty,'studyMethod':sm})

    return json_list



#从成绩表网页文件解析成绩表
def parse_scores_html(uid,html_file):
    try:
        data = html_file.read()
    except Exception as e:
        print('parse score read html error:',e)
        return None
    finally:
        html_file.close()

    table = BeautifulSoup(data,'html.parser').find('table',{'class':'ui_table ui_table_hover ui_table_striped ui_table_style02'})
    if table == None:
    	return None

    trs = table.find_all('tr')

    json_list = []
    for tr in trs:
    	item_list = tr.find_all('td')
    	if len(item_list) < 8:
    		continue

    	terms = item_list[1].get_text(strip = True).split(' ')

    	schoolYear = '--' if len(terms) < 2 else terms[0]
    	term = '--' if len(terms) < 2 else terms[1]

    	# term = '--' if len(item_list[1].get_text(strip = True)) == 0 else item_list[1].get_text(strip = True)
    	cid = '--' if len(item_list[2].get_text(strip = True)) == 0 else item_list[2].get_text(strip = True)
    	cn = '--' if len(item_list[3].get_text(strip = True)) == 0 else item_list[3].get_text(strip = True)

    	cty = '--' if len(item_list[4].get_text(strip = True)) == 0 else item_list[4].get_text(strip = True)
    	cp = '--' if len(item_list[5].get_text(strip = True)) == 0 else item_list[5].get_text(strip = True)

    	credit = 0.0 if len(item_list[6].get_text('|',strip = True).split('|')[0]) == 0 else float(item_list[6].get_text('|',strip = True).split('|')[0])
    	score = float(re.compile(r'\d{1,3}').findall(item_list[7].text)[0])
    	sm = '初修' if len(item_list[8].get_text(strip = True)) == 0 else item_list[8].get_text(strip = True)

    	json_list.append({'uid':uid,'schoolYear':schoolYear,'term':term,'cid':cid,'cname':cn,'type':cty,
    	'property':cp,'credit':credit,'score':score,'studyMethod':sm})

    return json_list


def parse_exams_html(uid,html_file):
    try:
        data = html_file.read()
    except Exception as e:
        print('parse score read html error:',e)
        return None
    finally:
        html_file.close()

    trs = BeautifulSoup(data,'html.parser').find_all('tr',class_='t_con')
    if len(trs) == 0:
        return None

    json_list = []
    for tr in trs:
        item_list = tr.find_all('td')

        if len(item_list)<10:
            continue

        cid = '--' if len(item_list[1].get_text(strip = True)) == 0 else item_list[1].get_text(strip = True)
        cn = '--' if len(item_list[2].get_text(strip = True)) == 0 else item_list[2].get_text(strip = True)
        cp = '--' if len(item_list[3].get_text(strip = True)) == 0 else item_list[3].get_text(strip = True)
        teacher = '--' if len(item_list[4].get_text(strip = True)) == 0 else item_list[4].get_text(strip = True)
        credit = 0.0 if len(item_list[5].get_text(strip = True)) == 0 else float(item_list[5].get_text(strip = True))

        # print('exam time is: ',item_list[6].get_text(strip = True))

        examTimes = item_list[6].get_text(strip = True).split(' ')

        ed = "待定" if len(examTimes) < 2 else examTimes[0]
        et = "待定" if len(examTimes) < 2 else examTimes[1]

        # et = '--' if len(item_list[6].get_text(strip = True)) == 0 else item_list[6].get_text(strip = True)

        exam_loc = item_list[7].get_text(strip = True).split('-')
        if len(exam_loc) == 3:
        	el = exam_loc[1]+'-'+exam_loc[2]
        else:
        	el = '--'

        ety = '--' if len(item_list[8].get_text(strip = True)) == 0 else item_list[8].get_text(strip = True)
        em = '--' if len(item_list[9].get_text(strip = True)) == 0 else item_list[9].get_text(strip = True)
        es = '--' if len(item_list[10].get_text(strip = True)) == 0 else item_list[10].get_text(strip = True)

        json_list.append({'uid':uid,'cid':cid,'cname':cn,'property':cp,'teacher':teacher,
        'credit':credit,'date':ed,'time':et,'classroom':el,'type':ety,'method':em,'status':es})

    return sort_list(json_list)


# 将数据排序，排序规则是：考过的降序排最后，没考的升序排前面
def sort_list(data_list):
    closed = []  # 已结束
    nobegin = [] # 未开始
    almost = []  # 即将开始
    other = []   #其他

    for item in data_list:
        if item.get('status')=='已结束':
            closed.append(item)
        elif item.get('status')=='未开始':
            nobegin.append(item)
        elif item.get('status')=='--':
            end_time = item.get('time').split('-')[1]
            end_date = item.get('date')

            end_time = datetime.datetime.strptime(end_date+" "+end_time,'%Y-%m-%d %H:%M')
            now_time = datetime.datetime.now()
            if now_time > end_time:# 如果已经结束了
                item['status']='已结束'
            # 后续版本可以增加正在考试中的状态
            almost.append(item)
        else:
            other.append(item)

    if closed != None:
        closed.reverse()
    return almost + nobegin + closed + other
